"""
预测历史模型
"""
from datetime import datetime
from app.extensions import db


class PredictionHistory(db.Model):
    """预测历史表"""
    __tablename__ = 'prediction_history'
    
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    student_id = db.Column(db.Integer, db.ForeignKey('student_profiles.id'), nullable=False, index=True)
    course_id = db.Column(db.Integer, db.ForeignKey('courses.id'))
    prediction_type = db.Column(db.Enum('grade', 'dropout', 'performance'), nullable=False)
    predicted_value = db.Column(db.Numeric(10, 4))
    confidence = db.Column(db.Numeric(5, 4))
    model_name = db.Column(db.String(50))
    features_used = db.Column(db.JSON)
    actual_value = db.Column(db.Numeric(10, 4))
    created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    
    # 关系
    student_profile = db.relationship('StudentProfile', backref='predictions')
    course = db.relationship('Course', backref='predictions')
    
    __table_args__ = (
        db.Index('idx_student_course_prediction', 'student_id', 'course_id'),
        db.Index('idx_created_at_desc', 'created_at', postgresql_using='btree'),
    )
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'student_id': self.student_id,
            'course_id': self.course_id,
            'prediction_type': self.prediction_type,
            'predicted_value': float(self.predicted_value) if self.predicted_value else None,
            'confidence': float(self.confidence) if self.confidence else None,
            'model_name': self.model_name,
            'features_used': self.features_used,
            'actual_value': float(self.actual_value) if self.actual_value else None,
            'created_at': self.created_at.isoformat() if self.created_at else None,
        }

